package com.hd.trans.ui.activity.customize

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Bundle
import android.text.InputFilter
import android.text.Spanned
import android.text.TextUtils
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.hd.trans.R
import com.hd.trans.TranslationUI
import com.hd.trans.callback.OnCompletionListener
import com.hd.trans.common.Constants
import com.hd.trans.common.interf.VoiceComposeListener
import com.hd.trans.config.TransConfigs
import com.hd.trans.databinding.ActivityTextTranslateBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.HuDunLanguage
import com.hd.trans.db.bean.TranslateRecord
import com.hd.trans.dialog.CustomConfirmDialog
import com.hd.trans.dialog.OfflinePkgProgressDialog
import com.hd.trans.extension.compatRemoveIf
import com.hd.trans.extension.observe
import com.hd.trans.extension.offlineLanguage
import com.hd.trans.framework.dialog.LanguageDialog
import com.hd.trans.framework.dialog.LanguageDialogType
import com.hd.trans.homefun.EventCode
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.network.component.HdTranslateComponent
import com.hd.trans.share.EnShareFileType
import com.hd.trans.share.ShareTextFileManager
import com.hd.trans.ui.activity.TextHistoryActivity
import com.hd.trans.ui.adapter.RecordTextAdapter2
import com.hd.trans.ui.base.LimitBaseActivity
import com.hd.trans.ui.model.TextTransViewModel
import com.hd.trans.utils.HtmlCompat
import com.hd.trans.utils.InputUtils
import com.hd.trans.utils.StringUtils
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.VoicePlayUtil
import com.hd.trans.utils.preference.Preferences
import com.hd.trans.widgets.VoicePlayView
import com.translation.assistant.callback.OnModelListener
import com.translation.assistant.data.OfflineConstant
import com.translation.assistant.manager.OfflineTranslatorManager
import kotlinx.android.synthetic.main.activity_text_translate.ll_history
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Objects

@SuppressLint("SetTextI18n")
class TextTranslateActivity: LimitBaseActivity() {
    private lateinit var mDataBinding: ActivityTextTranslateBinding
    private lateinit var mViewModel: TextTransViewModel
    //离线包下载管理器，不建议用懒加载，提前初始化时获取已下载离线包列表
    private lateinit var mOfflineManager: OfflineTranslatorManager
    private val needDownloadLanguages = LinkedHashSet<HuDunLanguage>()

    /**翻译组件*/
    private val mTranslateComponent by lazy {
        HdTranslateComponent(this)
    }
    /**tts播报组件*/
    private val voicePlayUtil by lazy {
        VoicePlayUtil.getInstance().apply {
            setOnCompletionListener(object : OnCompletionListener{
                override fun onCompletion(mp: MediaPlayer) {
                    mCurrentViewVoice?.stopPlay()
                }
            })
        }
    }
    /**分享组件*/
    private val shareMG by lazy {
        ShareTextFileManager(activity)
    }

    private val adapter by lazy {
        RecordTextAdapter2().apply {
            setOnItemClickListener { adapter, _, position ->
                val record = adapter.getItem(position)
                if (record != null && record is TranslateRecord) {
                    mViewModel.operateRecord.value = record
                }
            }
        }
    }

    private val activityLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult(),
        ActivityResultCallback<ActivityResult> { result ->
            when (result.resultCode) {
                Constants.TEXT_HISTORY_RESULT_OK -> if (result.data != null) {
                    val recordId = result.data!!
                        .getLongExtra(Constants.HISTORY_RECORD_ID, -1L)
                    if (recordId != -1L) {
                        mViewModel.getRecordById(recordId.toLong())
                    }
                }
            }
        })

    private val offlinePkgProgressDialog by lazy {
        OfflinePkgProgressDialog(this)
    }


    /**下载监听器*/
    private val modelDownloadListener =  object : OnModelListener<Void> {
        override fun onSuccess(languageCode: String, result: Void?) {
            //xxx语言翻译离线包下载完毕
            ToastUtils.showNormal("${OfflineConstant.getLanguageByCode(languageCode).name}语言翻译离线包下载完毕")
            needDownloadLanguages.compatRemoveIf { it.offlineLanguage().code == languageCode }
            if (needDownloadLanguages.isEmpty()) {
                offlinePkgProgressDialog.dismiss()
            }
        }

        override fun onFailure(languageCode: String, e: Exception?) { }

        override fun onProcess(languageCode: String, alreadyDownLength: Long, totalLength: Long) {

            val offlineTransFileSizeMap = TransConfigs.offlineTransFileSizeMap
            if (offlineTransFileSizeMap[languageCode] != totalLength){
                offlineTransFileSizeMap[languageCode] = totalLength
                TransConfigs.offlineTransFileSizeMap = offlineTransFileSizeMap
            }

            mXHandler.post {
                offlinePkgProgressDialog.updateProgress(languageCode,alreadyDownLength.toFloat() / totalLength)
            }
        }

    }

    /**
     * 下载翻译包提示弹窗
     */
    private val downloadOfflinePkgTipsDialog by lazy {
        CustomConfirmDialog(this,R.layout.trans_dlg_yes_or_no).apply {
            titleText = "翻译离线包下载"

            leftText = "取消"
            rightText = "下载"
            rightClick = {
                offlinePkgProgressDialog.setLanguages(needDownloadLanguages.toList())
                offlinePkgProgressDialog.show()

                needDownloadLanguages.forEach {
                    mOfflineManager.downloadModel(it.translateCode,"",modelDownloadListener)
                }

            }

        }
    }

    private var mCurrentViewVoice: VoicePlayView? = null

    private var mInputTextCache: String = ""
    private var isTextLineBreak:Boolean = true

    override fun getLayoutId(): Int {
        return R.layout.activity_text_translate
    }

    companion object {

        @JvmStatic
        fun open(context: Context, listener: LimitUseListener? = null) {
            limitListener = listener
            val intent = Intent(context, TextTranslateActivity::class.java)
            context.startActivity(intent)
        }
        @JvmStatic
        fun open(context: Context, recordId: Long, listener: LimitUseListener? = null) {
            limitListener = listener
            val intent = Intent(context, TextTranslateActivity::class.java)
            intent.putExtra("recordId", recordId)
            context.startActivity(intent)
        }
    }

    override val pageType: EventCode
        get() = EventCode.TEXT_TRANSLATE


    override fun onResume() {
        refreshHistoryRecords()
        super.onResume()
    }
    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_text_translate)
        mViewModel = ViewModelProvider(this).get(TextTransViewModel::class.java)
        mOfflineManager = OfflineTranslatorManager.getInstance(this)
        observe()
        initView()
        initData()
    }

    private fun observe() {
        observe(mViewModel.languageFrom) {
            mDataBinding.tvPreLang.text = it.name
        }

        observe(mViewModel.languageTo) {
            mDataBinding.tvPostLang.text = it.name
        }
        observe(mViewModel.detectLang) { language ->
            if (language != null && !compareLanguage(mViewModel.languageFrom.value,language)) {
                mDataBinding.tvLanguageDetect.text = language.name
                mDataBinding.layoutLanguageDetect.isVisible = true
            }else{
                mDataBinding.layoutLanguageDetect.isVisible = false
            }
        }
        observe(mViewModel.isLoading) {
            updateTranslateState(it)
        }
        observe(mViewModel.operateRecord) {
            if (it != null) {
                mViewModel.languageFrom.value = it.getLanguageFrom()
                mViewModel.languageTo.value = it.getLanguageTo()

                displayResult(true)
                mDataBinding.etInput.setText(it.contentOrig)
                mDataBinding.tvOriginal.text = getSplitText(it.contentOrig, it.pinyinOrig)
                mDataBinding.tvResult.text = getSplitText(it.contentTranslate, it.pinyinTranslate)
                updateCollectStatus(it.isCollected)
                languageDetect()
            }
        }
        observe(mViewModel.listTranslateRecord) { list ->
            mDataBinding.llHistory.alpha = if(list.isNullOrEmpty()) 0f else 1f
            if (!list.isNullOrEmpty()) {
                if (list.size > 3) {
                    //只获取前3条数据
                    val translateRecords = list.subList(0, 3)

                    adapter.setList(translateRecords)
                } else {
                    adapter.setList(list)
                }
            } else {
                adapter.setList(null)
            }
        }
    }

    /**
     * 更新收藏图标状态
     */
    private fun updateCollectStatus(isCollected: Boolean) {
        val collectDrawable:Int
        val tintColor: ColorStateList
        if (isCollected) {
            collectDrawable = R.mipmap.trans_collect2
            tintColor = ColorStateList.valueOf(Color.parseColor("#FFB016"))
        } else {
            collectDrawable = R.mipmap.trans_un_collect2
            tintColor = ColorStateList.valueOf(Color.parseColor("#161616"))
        }
        mDataBinding.btnCollect.setImageResource(collectDrawable)
        mDataBinding.btnCollect.imageTintList = tintColor
    }

    private fun initView() {
        mDataBinding.apply {
            click = this@TextTranslateActivity
            btnTranslate.isEnabled = false
            ivRomaTips.isVisible = Preferences.isShowPinyinTips
            swOffline.isChecked = Preferences.isOffline
            swOffline.setOnCheckedChangeListener { _, isChecked ->
                Preferences.isOffline = isChecked
                ToastUtils.showNormal("${if (isChecked) "已开启" else "已关闭"}离线翻译")
            }
        }
        initEdit()
        initAdapter()
        backHistoryRecords()
    }

    private fun getSplitText(text: String, pinyin: String?): CharSequence {
        if(pinyin.isNullOrEmpty()){
            return text
        }

        val textLines = text.split("\n")
        val pinyinLines = pinyin?.split("\n") ?: arrayListOf()
        val textBuilder = StringBuilder()
        for (i in textLines.indices){
            val line = textLines[i]
            val pinyinLine = if (i < pinyinLines.size) pinyinLines[i] else null
            //html的换行符
            val br = if (i < textLines.size - 1){
                "<br>"
            }else{
                ""
            }
            val hb = if (pinyinLine != null && pinyinLine.trim().isNotEmpty()) {
                "<font color='#A9A9A9'>$pinyinLine<br></font>$line$br"
            }else{
                line + br
            }
            textBuilder.append(hb)
        }
        val result = textBuilder.toString()
        val charSequence = HtmlCompat.fromHtml(result)
        return charSequence
    }

    private fun compareLanguage(lang1: HuDunLanguage?, lang2: HuDunLanguage?): Boolean {
        if (lang1 == null && lang2 == null) return true
        if (lang1 == null || lang2 == null) return false

        if (lang1.translateCode == lang2.translateCode) return true

        val branchRegex = "[（(].*[）)]$"
        val lang1Name = lang1.name.replace(branchRegex.toRegex(), "")
        val lang2Name = lang2.name.replace(branchRegex.toRegex(), "")

        return lang1Name == lang2Name
    }

    private fun initEdit() {
        val enterInputFilter: InputFilter = object : InputFilter {
            override fun filter(
                source: CharSequence?,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart:
                Int,
                dend: Int
            ): CharSequence? {
                if (isTextLineBreak) {
                    //如果允许换行则不处理
                    return null
                }

                return if (source == "\n"){
                    //如果是换行符
                    InputUtils.hideKeyboard(this@TextTranslateActivity)//隐藏软键盘
                    if (mDataBinding.etInput.text.toString().isNotEmpty()){
                        //startTranslate()
                    }
                    //返回空字符
                    ""
                } else{
                    //不处理
                    null
                }
            }
        }
        mDataBinding.apply {
            btnEmpty.isEnabled = false
            etInput.doAfterTextChanged {
                val text = it.toString()
                btnTranslate.isEnabled = text.isNotEmpty()
                btnEmpty.isEnabled = mInputTextCache.isNotEmpty() || text.isNotEmpty()
            }

            etInput.filters = arrayOf(enterInputFilter)
            etInput.hint = "请输入或粘贴需要翻译的文本"
            etInput.requestFocus()
            etInput.post {
                etInput.minHeight = svInputText.measuredHeight
            }
        }
    }

    private fun initAdapter() {
        mDataBinding.rvHistory.adapter = adapter
        mDataBinding.rvHistory.setLayoutManager(LinearLayoutManager(this))
    }

    private fun initData() {
        val fromLangName = PreferenceMgr.getInstance().translatePreference.tansFromLanguage
        val toLangName = PreferenceMgr.getInstance().translatePreference.tansToLanguage
        mViewModel.languageFrom.value = DataBaseMgr.getInstance().getLanguageByName(fromLangName)
        mViewModel.languageTo.value = DataBaseMgr.getInstance().getLanguageByName(toLangName)

        val recordId = intent.getLongExtra("recordId", -1L)
        if(recordId != -1L){
            mViewModel.getRecordById(recordId)
        }
    }

    /**
     * 加载动画
     */
    private fun updateTranslateState(isLoading: Boolean) {
        if (isLoading){
            showLoadDialog("翻译中...")
        }else{
            hideLoadDialog()
        }
    }

    private fun languageDetect(){
        if (!mDataBinding.layoutOriginResult.isVisible)
            return
        if ("自动检测" == mDataBinding.tvPreLang.text.toString())
            return
        mViewModel.languageDetect(mDataBinding.etInput.text.toString())
    }

    /**暂停语音播报*/
    private fun stopPlaying() {
        mCurrentViewVoice?.let {
            if(it.isPlaying())
                it.stopPlay()
        }
        voicePlayUtil.stopPlay()
    }

    /**
     * 刷新记录
     */
    private fun refreshHistoryRecords() {
        mViewModel.refreshRecords(false)
    }

    /**
     * 显示历史记录
     */
    private fun backHistoryRecords(){
        stopPlaying()
        displayResult(false)
    }

    /**
     * 显示翻译结果
     */
    private fun displayResult(isShow: Boolean){
        mDataBinding.layoutLanguageDetect.isVisible = false
        mDataBinding.rrResult.isVisible = isShow
        mDataBinding.llHistory.isVisible = !isShow
        mDataBinding.llCommon.isVisible = !isShow
        mDataBinding.layoutOriginResult.isVisible = isShow
        mDataBinding.layoutStartTranslate.isVisible = !isShow
        mDataBinding.tvOriginal.isVisible = isShow
        mDataBinding.etInput.isVisible = !isShow
    }

    /**
     * 清空原文
     */
    private fun empty() {
        mInputTextCache = mDataBinding.etInput.text.toString()
        mDataBinding.etInput.setText("")
        backHistoryRecords()
        if (mInputTextCache.isNotEmpty()){
            mDataBinding.btnEmpty.text = getString(R.string.undo_empty)
        }
    }

    /**
     * 恢复原文
     */
    private fun restore() {
        mDataBinding.etInput.setText(mInputTextCache)
        mDataBinding.etInput.setSelection(mInputTextCache.length)
        mDataBinding.btnEmpty.text = getString(R.string.clear_text)
        mInputTextCache = ""
    }

    /**分享文本*/
    private fun shareTxtFile() {
        val originalText = mDataBinding.tvOriginal.text.toString()
        val translatedText = mDataBinding.tvResult.text.toString()
        if(TextUtils.isEmpty(originalText.trim())
            && TextUtils.isEmpty(translatedText.trim())){
            ToastUtils.showNormal(resources.getString(R.string.tips_empty_content))
            return
        }
        shareMG.shareTextFile(
            StringUtils.template(originalText, translatedText),
            shareFileName(),
            EnShareFileType.TXT_FILE
        )
    }

    @SuppressLint("SimpleDateFormat")
    private fun shareFileName(): String? {
        val mFormat = SimpleDateFormat("yyyyMMdd_HHmmss")
        return mFormat.format(Date().time)
    }

    private fun showSelectLanguageDialog(isFromLang: Boolean) {
        val dialog = LanguageDialog(
            Objects.requireNonNull<HuDunLanguage?>(mViewModel.languageFrom.value),
            Objects.requireNonNull<HuDunLanguage?>(mViewModel.languageTo.value),
            isFromLang, LanguageDialogType.TEXT, LanguageDialogType.TO_TEXT
        )
        dialog.isOfflineLang = Preferences.isOffline
        dialog.show(supportFragmentManager, "LanguageDialog")
        dialog.setOnLanguageChangedListener(object : LanguageDialog.OnLanguageChangedListener{
            override fun onLanguageChanged(
                fromLanguage: HuDunLanguage,
                toLanguage: HuDunLanguage,
                selectedLanguage: HuDunLanguage
            ) {
                mViewModel.languageFrom.value = fromLanguage
                mViewModel.languageTo.value = toLanguage
                PreferenceMgr.getInstance().translatePreference
                    .saveTansFromLanguage(fromLanguage.name)
                PreferenceMgr.getInstance().translatePreference
                    .saveTansToLanguage(toLanguage.name)
            }
        })
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if ("自动检测" == mViewModel.languageFrom.value?.name) {
            return
        }
        val ta1 = TranslateAnimation(0f,
            (mDataBinding.btnFromLang.width + mDataBinding.btnSwitch.width).toFloat(),
            0f, 0f
        ).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.btnFromLang.startAnimation(ta1)
        mDataBinding.btnFromLang.bringToFront()
        val ta2 = TranslateAnimation(0f,
            (-mDataBinding.btnToLang.width - mDataBinding.btnSwitch.width).toFloat(),
            0f, 0f
        ).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.btnToLang.startAnimation(ta2)
        mDataBinding.btnToLang.bringToFront()
        ta1.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val fromTemp: HuDunLanguage? = mViewModel.languageFrom.value
                mViewModel.languageFrom.value = mViewModel.languageTo.value
                mViewModel.languageTo.value = fromTemp
                PreferenceMgr.getInstance().translatePreference
                    .saveTansFromLanguage(mViewModel.languageFrom.value?.name)
                PreferenceMgr.getInstance().translatePreference
                    .saveTansToLanguage(mViewModel.languageTo.value?.name)
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }


    private fun showDownloadOfflinePkgTipsDialog(){
        val contentTextBuilder = StringBuilder()
        contentTextBuilder.append("请先下载")
        var pos = 0
        needDownloadLanguages.forEach {
            if (pos != 0){
                contentTextBuilder.append("、")
            }
            contentTextBuilder.append(it.name)
            pos ++
        }
        contentTextBuilder.append("离线包！")
        downloadOfflinePkgTipsDialog.contentText = contentTextBuilder.toString()
        downloadOfflinePkgTipsDialog.show()
    }

    private fun translate() {
        mDataBinding.etInput.post {
            InputUtils.hideKeyboard(this)
        }
        val origContent = mDataBinding.etInput.text.toString()
        if (origContent.isEmpty()){
            return
        }

        // 检查是否有下载模型
        if (Preferences.isOffline){
            needDownloadLanguages.clear()
            if (!mOfflineManager.isModelDownloaded(mViewModel.languageFrom.value!!.offlineLanguage())){
                needDownloadLanguages.add(mViewModel.languageFrom.value!!)
            }
            if (!mOfflineManager.isModelDownloaded(mViewModel.languageTo.value!!.offlineLanguage())){
                needDownloadLanguages.add(mViewModel.languageTo.value!!)
            }

            if (needDownloadLanguages.isNotEmpty()){
                showDownloadOfflinePkgTipsDialog()
                return
            }
        }

        mViewModel.translationText(mTranslateComponent, origContent){
            consumeFreeTrial()
            //自动朗读
            if (PreferenceMgr.getInstance().translatePreference.voiceAuto){
                voicePlayback(mDataBinding.voicePlayTranslate, true)
            }
        }
    }

    /**
     * 语音播报
     */
    private fun voicePlayback(mVoicePlayView: VoicePlayView, isTransPart: Boolean) {

        if (voicePlayUtil.isPlaying) {
            voicePlayUtil.stopPlay()
        }
        if (mCurrentViewVoice != null) {
            mCurrentViewVoice!!.loadingComplete()
            if (mCurrentViewVoice!!.isPlaying()) {
                mCurrentViewVoice!!.stopPlay()
                if (mCurrentViewVoice == mVoicePlayView) return
            }
        }
        mCurrentViewVoice = mVoicePlayView

        val translateRecord = mViewModel.operateRecord.value
        if (translateRecord?.getLanguageFrom() == null
            || translateRecord.getLanguageTo() == null
            || TextUtils.isEmpty(translateRecord.contentTranslate)
            || TextUtils.isEmpty(translateRecord.contentOrig)
        ) {
            return
        }

        val content: String =
            if (isTransPart) translateRecord.contentTranslate else translateRecord.contentOrig
        val ttsCode: String = if (isTransPart) {
            if (translateRecord.isReverse) translateRecord.getLanguageFrom()
                .ttsCode else translateRecord.getLanguageTo().ttsCode
        } else {
            if (translateRecord.isReverse) translateRecord.getLanguageTo()
                .ttsCode else translateRecord.getLanguageFrom().ttsCode
        }
        voicePlayUtil.executeCompositeFile(ttsCode, content, object : VoiceComposeListener {
            override fun onStarting() {
                mCurrentViewVoice!!.loading()
            }

            override fun onCompleted(file: String, isLocal: Boolean) {
                mCurrentViewVoice!!.startPlay()
                voicePlayUtil.startPlay(file)
            }

            override fun onDownloadFailed() {
                mCurrentViewVoice!!.loadingFailed()
                voicePlayUtil.stopPlay()
            }
        })
    }

    override fun onBackPressed() {
        if (mDataBinding.rrResult.isVisible){
            backHistoryRecords()
        }else{
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        voicePlayUtil.destroy()
    }

    override fun onFastClick(v: View?) {
        mDataBinding.apply {
            when(v){
                //清空
                btnEmpty -> {
                    if (mInputTextCache.isNotEmpty()){
                        restore()
                    }
                    else{
                        empty()
                    }
                }
            }
        }
    }

    override fun onViewClick(v: View?) {
        mDataBinding.apply {
            when(v){
                //罗马读音提示
                ivRomaTips -> {
                    Preferences.isShowPinyinTips = false
                    ivRomaTips.isVisible = false
                }
                //返回
                back -> {
                    onBackPressed()
                }
                //快速切换成中英
                btnTagZhEn -> {
                    mViewModel.languageFrom.value = DataBaseMgr.getInstance()
                        .getLanguageByTransCode("zh")
                    mViewModel.languageTo.value = DataBaseMgr.getInstance()
                        .getLanguageByTransCode("en")
                }
                //快速切换成英中
                btnTagEnZh -> {
                    mViewModel.languageFrom.value = DataBaseMgr.getInstance()
                        .getLanguageByTransCode("en")
                    mViewModel.languageTo.value = DataBaseMgr.getInstance()
                        .getLanguageByTransCode("zh")
                }
                //切换源语言
                btnFromLang -> {
                    showSelectLanguageDialog(true)
                }
                //切换语言
                btnSwitch -> {
                    showTranslateAnimation()
                }
                //切换目标语言
                btnToLang -> {
                    showSelectLanguageDialog(false)
                }
                //设置
                btnSetting -> {
                    TranslationUI.openVoiceSettingActivity(
                        this@TextTranslateActivity,  false)
                }
                //开始翻译
                btnTranslate -> {
                    if (intercept(true, "开始翻译")){
                        return
                    }
                    translate()
                }
                //查看更多历史
                btnMoreHistory -> {
                    val intent = Intent(
                        this@TextTranslateActivity,
                        TextHistoryActivity::class.java
                    )
                    intent.putExtra("isFromTranslatePage", true)
                    activityLauncher.launch(intent)
                }
                //原文全屏浏览
                btnTopFullScreen -> {
                    TranslationUI.openFullScreenTransActivity(
                        this@TextTranslateActivity,
                        mDataBinding.tvOriginal.text.toString()
                    )
                }
                //译文全屏浏览
                btnBottomFullScreen -> {
                    TranslationUI.openFullScreenTransActivity(
                        this@TextTranslateActivity,
                        mDataBinding.tvResult.text.toString()
                    )
                }
                //删除
                btnDelete -> {
                    empty()
                }
                //分享
                btnShare -> {
                    shareTxtFile()
                }
                //收藏
                btnCollect -> {
                    mViewModel.collectRecord()
                }
                //复制
                btnCopy -> {
                    val cmb = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                    val mClipData = ClipData.newPlainText("翻译结果", mDataBinding.tvResult.text.toString())
                    cmb.setPrimaryClip(mClipData)
                    ToastUtils.showNormal("结果已复制")
                }
                //新建翻译
                btnNewTrans -> {
                    empty()
                }
                //原文语音播放
                voicePlayOrigin -> {
                    voicePlayback(voicePlayOrigin, false)
                }
                //译文语音播放
                voicePlayTranslate -> {
                    voicePlayback(voicePlayTranslate, true)
                }
            }
        }
    }

}